<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="query.productNo" clearable placeholder="产品编号" style="width: 130px;" class="filter-item"
        @keyup.enter.native="search" />
      <el-input v-model.trim="query.productName" clearable placeholder="产品名称" style="width: 130px;" class="filter-item"
        @keyup.enter.native="search" />
      <el-select v-model="query.itype" clearable placeholder="类型" class="filter-item" style="width: 130px">
        <el-option v-for="item in itypes" :key="item.key" :label="`${item.displayName}`" :value="item.key" />
      </el-select>
      <el-select v-model="query.istatus" clearable placeholder="状态" class="filter-item" style="width: 130px">
        <el-option v-for="item in search_status" :key="item.key" :label="`${item.displayName}`" :value="item.key" />
      </el-select>
      <el-button style="margin-left:20px;" class="filter-item" type="primary" icon="el-icon-search" @click="search">{{
        $t('table.search') }}</el-button>
      <!--<el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          @click="geterp"
         >ERP拉取</el-button>-->
      <!--<el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-edit"
          @click="handleAdd"
        >{{ $t('table.add') }}</el-button>-->
      <!--<el-upload
                style="display:inline-block"
          :on-change="fileChange"
            class="filter-item"
           action=""
          ref="upload1"

          :before-upload="beforeUploadNew"
          :limit='1'

            :on-exceed="handleExceed"
             :file-list="fileList"
            :http-request="((e)=>{uploadActionUrl(e)})">
            <el-button    icon="el-icon-upload" type="primary" class="filter-item"
            style="margin-top: 10px;">{{$t('permission.excelImport')}}</el-button>
          </el-upload> -->
    </div>

    <el-table v-loading="loading" :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="id"
      highlight-current-row border>
      <el-table-column prop="productNo" label="产品编号" width="200" />
      <el-table-column prop="productName" label="产品名称" width="500" />
      <el-table-column prop="pversion" label="版本号" />
      <el-table-column prop="specification" label="规格型号" />
      <el-table-column prop="auxprop" label="辅助属性" />
      <el-table-column prop="itype" label="类型">
        <template slot-scope="{row}">
          <span>{{ formatType(row.itype) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="istatus" label="状态">
        <template slot-scope="{row}">
          <span>{{ formatStatus(row.istatus) }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column prop="lineCapacity" label="产线产能" sortable />-->
      <el-table-column label="创建时间" width="150" sortable prop="createTime">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" :label="$t('table.actions')" align="center">
        <template slot-scope="{row,$index}">
          <!--<el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>-->
          <el-button size="mini" type="danger" @click="handleDelete(row, $index)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />

    <el-dialog :before-close="handleClose" :close-on-click-modal="false" :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑' : '新增'" width="70%">
      <el-form ref="ruleForm" :model="product" label-width="100px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称">
              <el-input v-model.trim="product.productName" placeholder="产品名称" maxlength="50"
                :disabled="dialogType === 'edit' && product.dataFrom == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编号">
              <el-input v-model.trim="product.productNo" disabled placeholder="产品编号" style="width:320px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model.trim="product.projectName" placeholder="项目名称" style="width:420px" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型">
              <el-select v-model="product.itype" placeholder="类型" class="filter-item" style="width: 130px">
                <el-option v-for="item in itypes" :key="item.key" :label="`${item.displayName}`" :value="item.key" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态" prop="istatus">
              <el-select v-model="product.istatus" placeholder="状态" class="filter-item" style="width: 130px"
                :disabled="dialogType === 'edit' && product.dataFrom == 1">
                <el-option v-for="item in istatusList" :key="item.key" :label="`${item.displayName}`"
                  :value="item.key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="pversion">
              <el-input v-model.trim="product.pversion" placeholder="版本号" style="width:420px" maxlength="50"
                :disabled="dialogType === 'edit' && product.dataFrom == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model.trim="product.specification" placeholder="规格型号" style="width:420px" maxlength="50"
                :disabled="dialogType === 'edit' && product.dataFrom == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="辅助属性" prop="auxprop">
              <el-input v-model.trim="product.auxprop" placeholder="辅助属性" style="width:420px" maxlength="50"
                :disabled="dialogType === 'edit' && product.dataFrom == 1" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row />

        <el-form-item label="产线/工位">
          <el-table v-loading="loadinginner" :data="detailList" border fit highlight-current-row
            style="width: 100%; margin:30px 0;">
            <el-table-column min-width="250px" align="center" label="产线">
              <template slot-scope="{row,$index}">

                <el-select v-model="row.linecode" filterable placeholder="请选择产线" @change="getline1($index)">
                  <el-option v-for="item in lineList" :key="item.value" :label="item.lineName" :value="item.lineCode" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column min-width="250px" align="center" label="产能">
              <template slot-scope="{row}">
                <el-input v-model="row.lineCapacity" style="width:200px" maxlength="4"
                  oninput="value=value.replace(/^0|[^0-9]/g, '')" placeholder="产能">
                  <i slot="suffix"
                    style="font-style:normal;margin-right: 10px;position:absolute;top:8px;right:0px;">件</i>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column min-width="250px" align="center" label="工位">
              <template slot-scope="{row,$index}">
                <el-select v-model="row.lineType4List" multiple :disabled="!row.linecode" clearable filterable
                  reserve-keyword placeholder="请选择工位" style="width: 100%" default-first-option>
                  <el-option v-for="(item, index) in lineListdown[$index].linedown" :key="index" :label="item.lineName"
                    :value="item.lineCode" />
                </el-select>

              </template>
            </el-table-column>
            <el-table-column align="center" width="240">
              <template slot="header">
                <img src="../../../images/tianjia.png" style="width:25px;" @click="addMaterialDetail">
                <!--<el-button   type="primary" @click="saveMaterialDetail">保存</el-button>-->
              </template>
              <template slot-scope="scope">
                <div>
                  <div>
                    <img src="../../../images/jianhao.png" style="width:25px;" @click="deleteRow(scope.$index)">
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-upload ref="upload1" :before-upload="beforeUpload" style="display:inline-block" class="filter-item"
            action="" multiple :limit="1" :on-exceed="handleExceedOrder" :http-request="uploadActionUrl">
            <el-button icon="el-icon-upload" type="primary" class="filter-item">上传作业指导书</el-button>
          </el-upload>
          <el-table :data="fileList" style="width: 100% ;" row-key="id" highlight-current-row border>
            <el-table-column prop="fileName" label="文件名称" sortable />
            <el-table-column label="状态">
              <template slot-scope="{ row }">
                <span v-if="row.status == 1">有效</span>
                <span v-if="row.status == 0">作废</span>
              </template>
            </el-table-column>
            <el-table-column label="上传时间">
              <template slot-scope="{ row }">
                <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.actions')" align="center">
              <template slot-scope="{ row }">
                <el-button type="primary" size="mini" @click="handleShowProjectFile(row)">
                  查看
                </el-button>
                <el-button type="danger" size="mini" @click="handleCancelFile(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div style="text-align:center;">
        <el-button type="danger" @click="handleClose1">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="confirm">{{ $t('permission.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { geterpfun, getInfo, add, update, deleteInfo, addImg, importexcel, mopLineDown, impProductionPlanData, getuploadfile, downloadPing, deletefile } from '@/api/product'
import { getMopLine3 } from '@/api/moplineManager'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { deepClone, Compare, isObjectEqual } from '../../../utils'

const product = {
  id: 0,
  productNo: '',
  productName: '',
  pversion: '',
  picAddress: '',
  material: '',
  prop: '',
  auxprop: '',
  specification: '',
  unit: '',
  success: 0,
  productHour: 0,
  replaceHour: 0,
  replaceQA: 0,
  exchangeHour: 0,
  exchangeQA: 0,
  pushHour: 0,
  pushQA: 0,
  tapHour: 0,
  tapQA: 0,
  moveHour: 0,
  pullHour: 0,
  totalOtherHour: 0,
  bomCode: '',
  errorMsg: '',
  itype: 1,
  istatus: 1,
  createUserId: 0,
  createTime: new Date().getTime(),
  updateUserId: 0,
  updateTime: new Date().getTime(),
  line: [],
  lineCapacity: '',
  loadinginner: true

}
const _detail = {
  // id: null,
  linecode: '',
  lineType4List: ''
}
export default {
  name: 'Product',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      line: [],

      rules: {

        productHour: [
          { required: true, message: '请填写单件生产工时', trigger: 'blur' }
        ],
        line: [
          { required: true, message: '请选择产线编号', trigger: 'blur' }
        ],
        lineCapacity: [
          { required: true, message: '请填写产线产能', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      dialogType: 'new',
      total: 0,
      product: Object.assign({}, product),
      search_status: [
        // { key: '', displayName: '全部' },
        // { key: 0, displayName: '新增' },
        { key: 1, displayName: '启用' },
        { key: 0, displayName: '禁用' }
      ],
      search_itypes: [
        { key: -1, displayName: '全部' },
        { key: 1, displayName: '钣金件' }
      ],
      istatusList: [{ key: 1, displayName: '启用' }, { key: 0, displayName: '禁用' }],
      status: [
        // { key: 0, displayName: '新增' },
        { key: 1, displayName: '启用' },
        { key: 0, displayName: '禁用' }
      ],
      itypes: [{ key: 1, displayName: '量产' }, { key: 2, displayName: '样机' }, { key: 3, displayName: '其他' }],
      query: {

        pageIndex: 1,
        pageSize: 20,
        productNo: '',
        istatus: 1
        // createTimeS: '',
        // createTimeE: ''
      },
      tableData: [],
      AssistTurnList: [{ id: 0, assistTurnName: '请选择辅助工序' }],
      fileList: [],
      lineList: [],
      detailList: [],
      lineListdown: [],
      origindata: [],
      loading: true,
      fullscreenLoading: false,
      showerp: false
    }
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    geterp() {
      if (!this.showerp) {
        geterpfun(this.product.id).then(res => {
          this.showerp = true
          this.fileList = res.data
          this.fullscreenLoading = false
          setTimeOut(() => {
            this.showerp = false
          }, 20000)
        }).catch(err => {
          this.fullscreenLoading = false
        })
      } else {
        this.$message({
          message: '请勿频繁操作',
          type: 'error'
        })
      }
    },
    beforeUpload(file) {
      const size10M = file.size / 1024 / 1024 <= 5
      if (!size10M) {
        this.$message.warning('上传文件大小不能超过 5MB!')
        return false
      }
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = ['txt', 'doc', 'docx', 'xls', 'xlsx', 'pdf', 'jpg', 'jpeg', 'zip', 'rar', '7z']
      if (extension.indexOf(testmsg) == -1) {
        this.$message({
          message: '上传文件只能是.TXT、.DOC、.DOCX、.XLS、.XLSX、.PDF、.JPG、ZIP、 RAR、 7Z、JPEG格式!',
          type: 'warning'
        })
        return false
      }
    },
    handleCancelFile(row) {
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await deletefile(row.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })

          this.getuploadfileFun()
        })
        .catch((err) => console.error(err))
    },
    handleShowProjectFile(row) {
      downloadPing(row.id).then(res => {
        const content = res
        const blob = new Blob([content]) // 构造一个blob对象来处理数据
        const fileName = row.fileName // 导出文件名
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
      })
      // window.location.href = process.env.VUE_APP_BASE_API + ':' + window.localStorage.getItem('port')+ '/needchange/downloadFile/' + row.id
    },
    getuploadfileFun() {
      this.fullscreenLoading = true
      getuploadfile(this.product.id).then(res => {
        this.fileList = res.data
        this.fullscreenLoading = false
      }).catch(err => {
        this.fullscreenLoading = false
      })
    },
    uploadActionUrl(item) {
      const fileObj = item.file
      const form = new FormData()
      form.append('file', fileObj)
      this.fullscreenLoading = true
      impProductionPlanData(form, this.product.id).then((response) => {
        if (response.isSuccess == true) {
          this.getInfo()
          this.$message.info('文件：' + fileObj.name + '上传成功')
          this.showImportOrder = false
          this.$refs.upload1.clearFiles()
          this.getuploadfileFun()
        } else {
          this.$message({
            showClose: true,
            duration: 120000,
            type: 'error',
            message: response.data[0]
          })
        }
      }).catch(err => {
        this.fullscreenLoading = false
      })
    },
    handleClose(done) {
      var res = isObjectEqual(this.origindata, this.detailList)
      if (res) {
        done()
      } else {
        this.$confirm('产线/工位信息修改后未保存,确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      }
    },
    handleClose1(done) {
      var res = isObjectEqual(this.origindata, this.detailList)
      if (res) {
        this.dialogVisible = false
      } else {
        this.$confirm('产线/工位信息修改后未保存,确认关闭？')
          .then(_ => {
            this.dialogVisible = false
          })
          .catch(_ => { })
      }
    },
    getline(index) {
      if (this.detailList1[index].linecode) {
        mopLineDown(this.detailList1[index].linecode).then(res => {
          this.lineListdown[index].linedown = res.data
          if (index == this.detailList1.length - 1) {
            this.detailList = deepClone(this.detailList1)
            this.loadinginner = false
          }
        })
      }
    },
    getline1(index) {
      if (this.detailList[index].linecode) {
        mopLineDown(this.detailList[index].linecode).then(res => {
          if (res.isSuccess) {
            this.lineListdown[index].linedown = res.data

            const str = []
            if (this.lineListdown[index].linedown.length > 0) {
              for (var i = 0; i < this.lineListdown[index].linedown.length; i++) {
                str.push(this.lineListdown[index].linedown[i].lineCode)
              }

              this.detailList[index].lineType4List = str
            }
          } else {
            this.$message.error(res.message)
            this.lineListdown[index].linedown = []
            this.detailList[index].lineType4List = []
          }
        })
      }
    },
    deleteRow(index) {
      this.detailList.splice(index, 1)
      this.lineListdown.splice(index, 1)
    },
    formatMaterial() {

    },
    saveMaterialDetail() {

    },
    addMaterialDetail() {
      const materialDetailItem = Object.assign({}, _detail)

      this.lineListdown.push({
        linedown: []
      })
      this.detailList.push(materialDetailItem)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`每次只能上传一个文件`)
    },
    beforeUploadNew(file) {
      const size10M = file.size / 1024 / 1024 <= 5
      if (!size10M) {
        this.$message.warning('上传文件大小不能超过 5MB!')
        return false
      }
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = ['xls', 'xlsx']
      if (extension.indexOf(testmsg) == -1) {
        this.$message({
          message: '上传文件只能是.XLS、.XLSX格式!',
          type: 'warning'
        })
        return false
      }
    },

    changLine() {
      this.product.canUseLines = this.product.line.toString()
    },
    getlineList() {
      getMopLine3().then((res) => {
        this.lineList = res.data
      })
    },
    getInfo() {
      this.loading = true
      getInfo(this.query).then(res => {
        this.loading = false
        this.tableData = res.data.items
        this.total = res.data.totalItems
      })
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    handleAdd() {
      this.product = Object.assign({}, product)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.getlineList()
    },
    handleUpdate(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.product = deepClone(row)

      this.getlineList()
      this.origindata = []
      this.lineListdown = []
      this.detailList = []

      if (row.lineList) {
        this.loadinginner = true
        this.origindata = deepClone(row.lineList)
        this.detailList1 = deepClone(row.lineList)
        for (var i = 0; i < this.detailList1.length; i++) {
          this.lineListdown.push({ linedown: [] })
          this.getline(i)
        }
      }
      this.getuploadfileFun()
    },
    handleDelete(row, $index) {
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          deleteInfo(row.id).then(res => {
            if (res.isSuccess) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }

            this.getInfo()
          })
        })
        .catch(err => console.error(err))
    },
    onBeforeUploadImage(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/jpg' || 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!')
      }
      return isIMAGE && isLt1M
    },
    UploadImage(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      addImg(formData)
        .then(response => {
          this.product.picAddress = response.data

          param.onSuccess() // 上传成功的图片会显示绿色的对勾
          // 但是我们上传成功了图片， fileList 里面的值却没有改变，还好有on-change指令可以使用
        })
    },
    confirm() {
      const isEdit = this.dialogType === 'edit'
      this.product.lineList = this.detailList
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const arr = []
          for (var i = 0; i < this.detailList.length; i++) {
            if (!this.detailList[i].linecode) {
              this.$notify({
                title: 'error',
                dangerouslyUseHTMLString: true,
                message: `
                    <div>请选择产线</div>
                   
                  `,
                type: 'error'
              })
              return false
            }
            if (!this.detailList[i].lineCapacity) {
              this.$notify({
                title: 'error',
                dangerouslyUseHTMLString: true,
                message: `
                    <div>请完善产能信息</div>
                   
                  `,
                type: 'error'
              })
              return false
            }
            if (this.detailList[i].lineType4List.length == 0) {
              this.$notify({
                title: 'error',
                dangerouslyUseHTMLString: true,
                message: `
                    <div>请选择工位</div>
                   
                  `,
                type: 'error'
              })
              return false
            }
            arr.push(this.detailList[i].linecode)
          }

          const new_arr = Array.from(new Set(arr))
          if (new_arr.length < arr.length) {
            this.$notify({
              title: 'error',
              dangerouslyUseHTMLString: true,
              message: `
                    <div>不能添加相同的产线</div>
                   
                  `,
              type: 'error'
            })
            return false
          }
          if (isEdit) {
            update(this.product.id, this.product).then((res) => {
              if (res.isSuccess) {
                this.getInfo()
                this.dialogVisible = false
                const { productNo, productName } = this.product
                //  this.$message.success('编辑cheng'go'g!')
                this.$notify({
                  title: 'Success',
                  dangerouslyUseHTMLString: true,
                  message: `
                    <div>产品编号: ${productNo}</div>
                    <div>产品名称: ${productName}</div>
                  `,
                  type: 'success'
                })
              } else {
                this.$notify({
                  title: 'error',
                  dangerouslyUseHTMLString: true,
                  message: `<div>保存失败</div>,` + res.meaaage,
                  type: 'error'
                })
              }
            })
          } else {
            add(this.product).then((res) => {
              if (res.isSuccess) {
                this.getInfo()
                this.dialogVisible = false
                const { productNo, productName } = this.product
                this.$notify({
                  title: 'Success',
                  dangerouslyUseHTMLString: true,
                  message: `
            <div>产品编号: ${productNo}</div>
            <div>产品名称: ${productName}</div>
          `,
                  type: 'success'
                })
              } else {
                this.$notify({
                  title: 'error',
                  dangerouslyUseHTMLString: true,
                  message: `<div>保存失败</div>,` + res.meaaage,
                  type: 'error'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    formatStatus(key) {
      const rt = this.status.find(rt => rt.key === key)
      return rt ? rt.displayName : ''
    },
    formatType(key) {
      const rt = this.itypes.find(rt => rt.key === key)
      return rt ? rt.displayName : ''
    }
  }
}
</script>
